package com.qersoft.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qersoft.dao.PersonalScoreAnalysisDao;
import com.qersoft.entity.PersonalScoreAnalysisEntity;
import com.qersoft.entity.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service("PersonalScoreAnalysisService")
public class PersonalScoreAnalysisServiceImpl implements PersonalScoreAnalysisService {

    @Autowired
    private PersonalScoreAnalysisDao scoreAnalysisDao;


    // 添加学生的成绩分析
    @Override
    public Boolean createPersonalScoreAnalysis(PersonalScoreAnalysisEntity personalScoreAnalysisEntity) {
        return scoreAnalysisDao.insert(personalScoreAnalysisEntity) > 0;
    }

    // 获取某个学生的成绩分析
    @Override
    public PersonalScoreAnalysisEntity getScoreAnalysis(Long studentId, Long examId) {
        return scoreAnalysisDao.selectById(studentId);
    }

    // 获取班级的成绩分析
    @Override
    public List<PersonalScoreAnalysisEntity> getClassScoreAnalysis(Long examId) {
        return scoreAnalysisDao.selectList(new QueryWrapper<PersonalScoreAnalysisEntity>().eq("exam_id", examId));
    }

    // 更新成绩分析
    @Override
    public boolean updateScoreAnalysis(PersonalScoreAnalysisEntity scoreAnalysisEntity) {
        return scoreAnalysisDao.updateById(scoreAnalysisEntity) > 0;
    }

    // 删除某个学生的成绩分析
    @Override
    public boolean deleteScoreAnalysis(Long studentId, Long examId) {
        return scoreAnalysisDao.delete(new QueryWrapper<PersonalScoreAnalysisEntity>().eq("student_id", studentId).eq("exam_id", examId)) > 0;
    }

    @Override
    public ResponseMessage<String> calculateScoreChange(Long studentId, String subject) {
        // 获取该学生某一学科的成绩分析记录，按考试ID升序排列
        List<PersonalScoreAnalysisEntity> scoreList = scoreAnalysisDao.selectList(
                new QueryWrapper<PersonalScoreAnalysisEntity>()
                        .eq("student_id", studentId)
                        .eq("subject", subject)  // 根据学科筛选
                        .orderByAsc("exam_id"));  // 按照考试ID升序排列

        // 如果成绩记录不足两条，无法计算进步或退步
        if (scoreList == null || scoreList.size() < 2) {
            return ResponseMessage.message("无法计算进步或退步，历史成绩不足");
        }
        PersonalScoreAnalysisEntity currentScore = scoreList.get(scoreList.size() - 1);
        PersonalScoreAnalysisEntity lastScore = scoreList.get(scoreList.size() - 2);

        // 计算成绩和排名的变化
        BigDecimal scoreChange = currentScore.getScore().subtract(lastScore.getScore());
        BigDecimal rankChange = currentScore.getStudentRank().subtract(lastScore.getStudentRank());

        String result;
        if (scoreChange.compareTo(BigDecimal.ZERO) > 0) {
            result = studentId + " 在学科 " + subject + " 中进步了 " + rankChange.abs() + " 名";
        } else if (scoreChange.compareTo(BigDecimal.ZERO) < 0) {
            result = studentId + " 在学科 " + subject + " 中退步了 " + rankChange.abs() + " 名";
        } else {
            result = "在学科 " + subject + " 中，成绩和排名没有变化";
        }
        return ResponseMessage.message(result);
    }


    // 计算学生的平均成绩
    @Override
    public ResponseMessage<BigDecimal> calculateAverageScore(Long studentId) {
        // 获取该学生所有成绩分析记录
        List<PersonalScoreAnalysisEntity> scoreList = scoreAnalysisDao.selectList(new QueryWrapper<PersonalScoreAnalysisEntity>().eq("student_id", studentId));
        if (scoreList == null || scoreList.isEmpty()) {
            return ResponseMessage.message(BigDecimal.ZERO);  // 没有成绩则返回0
        }
        BigDecimal totalScore = BigDecimal.ZERO;
        int totalExams = scoreList.size();
        // 计算总分
        for (PersonalScoreAnalysisEntity scoreAnalysis : scoreList) {
            totalScore = totalScore.add(scoreAnalysis.getScore());
        }
        // 计算平均分
        BigDecimal averageScore = totalScore.divide(BigDecimal.valueOf(totalExams), 2, BigDecimal.ROUND_HALF_UP);
        return ResponseMessage.message(averageScore);
    }

    // 计算学生的总成绩
    @Override
    public ResponseMessage<BigDecimal> calculateTotalScore(Long studentId) {
        // 获取该学生所有成绩分析记录
        List<PersonalScoreAnalysisEntity> scoreList = scoreAnalysisDao.selectList(new QueryWrapper<PersonalScoreAnalysisEntity>().eq("student_id", studentId));
        if (scoreList == null || scoreList.isEmpty()) {
            return ResponseMessage.message(BigDecimal.ZERO);  // 没有成绩则返回0
        }
        BigDecimal totalScore = BigDecimal.ZERO;
        // 计算总分
        for (PersonalScoreAnalysisEntity scoreAnalysis : scoreList) {
            totalScore = totalScore.add(scoreAnalysis.getScore());
        }

        return ResponseMessage.message(totalScore);  // 返回总分
    }

    // 获取学生的排名
    @Override
    public ResponseMessage<Integer> getRank(Long studentId) {
        // 获取该学生的总成绩
        BigDecimal studentTotalScore = this.calculateTotalScore(studentId).getData();
        // 获取所有学生的总成绩
        List<PersonalScoreAnalysisEntity> allScores = scoreAnalysisDao.selectList(new QueryWrapper<>());
        // 按照总成绩降序排列
        allScores.sort((score1, score2) -> score2.getScore().compareTo(score1.getScore()));
        int rank = 1;  // 默认学生的排名是1
        for (PersonalScoreAnalysisEntity scoreAnalysis : allScores) {
            if (scoreAnalysis.getStudentId().equals(studentId)) {
                return ResponseMessage.message(rank);
            }
            rank++;
        }
        return ResponseMessage.message(-1);  // 如果没有找到学生的成绩，返回-1
    }
}
